const Koa = require("koa");
const cors = require("koa-cors");
const path = require("path");
const bodyParser = require("koa-bodyparser");
const logger = require("koa-logger");
const { JWT_SECRET, port } = require("./config");
const koajwt = require("koa-jwt");
const KoaBody = require("koa-body");
const KoaStatic = require("koa-static");
const router = require("./router");
const { wirteJSON } = require("./utils/func");

const _dirname = path.resolve();
const app = new Koa();

//上传图片/文件 必须写在跨域前面，原因暂时还没明白
app.use(
  KoaBody({
    multipart: true, //开启支持 文件上传
    formidable: {
      //关于文件上传的相关配制
      // 在配制选项option里, 不推荐使用相对路径
      // 在option里的相对路径, 不是相对的当前文件. 相对process.cwd()
      uploadDir: path.join(_dirname, "/public/uploads/"),
      //允许保留后缀名
      keepExtensions: true,
      multipart: true,
    },
    jsonLimit: "10mb",
    formLimit: "10mb",
    textLimit: "10mb",
    parsedMethods: ["POST", "PUT", "PATCH", "DELETE"],
  })
);
// post参数
app.use(bodyParser());
app.use(KoaStatic(path.join(_dirname, "/public")));
// 跨域处理
app.use(cors());
app.use(logger());

app.use(function (ctx, next) {
  return next().catch((err) => {
    if (401 == err.status) {
      wirteJSON(ctx, 302, "身份验证失败，请重新登入！", null);
    } else {
      throw err;
    }
  });
});

app.use(
  koajwt({
    secret: JWT_SECRET,
  }).unless({
    // 配置白名单
    path: [/\/user\/register/, /\/user\/login/],
  })
);

app.use(router.routes(), router.allowedMethods());
app.listen(port, () => {
  console.log(`server is alerday ${port} start`);
});
